package io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.*;

@Slf4j
public class BIOClient {
    public static void main(String[] args) {
        String serverName = "127.0.0.1";
        int port = 8888;

        try {
            // 创建套接字并连接到服务器
            Socket clientSocket = new Socket(serverName, port);

            // 获取输入输出流
            OutputStream outputStream = clientSocket.getOutputStream();
            InputStream inputStream = clientSocket.getInputStream();

            // 创建写入器和读取器
            PrintWriter writer = new PrintWriter(outputStream, true);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 用户可以多次输入
            while (true) {
                // 等待用户输入
                BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
                String message = userInput.readLine();
                log.info("用户输入：{}", message);
                writer.println(message);
                writer.flush();

                // `从服务器接收响应并打印`
                String response = reader.readLine();
                log.info("服务器响应：{}", response);

                if ("exit".equals(message)) {
                    break;
                }
            }

            // 关闭连接
            clientSocket.close();
            log.info("客户端关闭连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}